<script setup>
import { ref } from 'vue'
import PageContainer from '@/components/PageContainer.vue'
import { userUpdatePwdService } from '@/api/user'
import { useuserStore } from '@/stores'
import { useRouter } from 'vue-router'
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})
const form = ref()
const formRules = {
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
    { validator: validateDifferentPassword, trigger: 'blur' }
  ],
  re_pwd: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
    { validator: validatePasswordMatch, trigger: 'blur' }
  ]
}

function validateDifferentPassword(rule, value, callback) {
  if (value === pwdForm.value.old_pwd) {
    callback(new Error('新密码不能与原密码相同'))
  } else {
    callback()
  }
}

function validatePasswordMatch(rule, value, callback) {
  if (value !== pwdForm.value.new_pwd) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}
const user = useuserStore()
const router = useRouter()
const submitForm = async () => {
  const validate = await form.value.validate()
  if (validate) {
    await userUpdatePwdService(pwdForm.value)
    ElMessage.success('修改成功')
    user.removeuserInfo({})
    user.removeuserToken()
    router.push('/login')
  }
}

const resetForm = () => {
  form.value.resetFields()
}
</script>
<template>
  <PageContainer title="修改密码">
    <el-form
      ref="form"
      :model="pwdForm"
      :rules="formRules"
      label-width="100px"
      class="pwd-form"
      style="width: 50%"
    >
      <el-form-item label="原密码" prop="old_pwd">
        <el-input
          type="password"
          v-model="pwdForm.old_pwd"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input
          type="password"
          v-model="pwdForm.new_pwd"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="re_pwd">
        <el-input
          type="password"
          v-model="pwdForm.re_pwd"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">修改密码</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </PageContainer>
</template>
